import React, {Component} from 'react';
import {StyleSheet, Text, View, TouchableOpacity} from 'react-native';

import DateTimePickerModal from 'react-native-modal-datetime-picker';
import {formatDateTimeByISOTime} from './format';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';

export default class extends Component {
  constructor(props) {
    super(props);
  }
  componentDidMount() {
    this.updateValue(this.props);
  }
  state = {
    show: false,
    lazyValue: null,
  };
  hide() {
    this.setState({
      show: false,
    });
  }
  updateValue(props) {
    const {value} = props;
    const {lazyValue} = this.state;
    if (value !== lazyValue) {
      this.setState({
        lazyValue: value,
      });
    }
    if (!value && !lazyValue) {
      this.setState({});
    }
  }
  UNSAFE_componentWillReceiveProps(newProps) {
    this.updateValue(newProps);
  }
  render() {
    const {value, onValueChange, disabled} = this.props;
    const {show} = this.state;
    return (
      <>
        <View style={styles.container}>
          <TouchableOpacity
            style={styles.input}
            onPress={() => {
              this.setState({
                show: true,
              });
            }}>
            {value ? (
              <Text>{formatDateTimeByISOTime(value)}</Text>
            ) : (
              <Text>請選擇</Text>
            )}
          </TouchableOpacity>
          <TouchableOpacity
            disabled={disabled}
            onPress={onValueChange && onValueChange.bind(this, null)}
            style={styles.clearContainer}>
            <Icon name="close-circle" size={15} />
          </TouchableOpacity>
        </View>
        <DateTimePickerModal
          isVisible={show}
          mode="datetime"
          locale="zh"
          date={value ? new Date(value) : new Date()}
          onConfirm={(v) => {
            this.hide();
            const v1 = v.toISOString() || v;
            onValueChange && onValueChange(v1);
          }}
          onCancel={this.hide.bind(this)}
        />
      </>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  input: {
    flex: 1,
  },
  modal: {
    justifyContent: 'flex-end',
    margin: 0,
  },
  content: {
    backgroundColor: '#fff',
    maxHeight: 400,
  },
  actionBtn: {},
  actionBar: {
    height: 50,
    flexDirection: 'row',
    justifyContent: 'space-between',
    padding: 10,
  },
  clearContainer: {
    padding: 5,
  },
});
